/*
 * @User 		@Company 	@Date
 * marcusbui	VNNET24  	Jun 19, 2011
 */
package tsb.com.html5.controller.common;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import tsb.com.html5.common.service.ICommonService;
import tsb.com.html5.controller.base.BaseController;
import tsb.com.html5.file.item.FileItem;

// TODO: Auto-generated Javadoc
/**
 * The Class ImageController.
 */
@Controller
@RequestMapping("/file")
public class FileController extends BaseController{

	/** The common service. */
	@Resource(name="CommonService")
	private ICommonService commonService;
	
	/**
	 * Gets the image.
	 *
	 * @param id the id
	 * @param req the req
	 * @param res the res
	 * @return the image
	 * @throws Exception the exception
	 */
	@RequestMapping(value="/image", method = RequestMethod.GET)
	public void getImage(@RequestParam("id") String id,
			HttpServletRequest req, HttpServletResponse res) throws Exception {
		
		InputStream is = null;
		try {
			if (id == null) {
				return;
			}

			/*GetFileParam parm = new GetFileParam(); 
			parm.setFileId(id);
			FileItem file = commonService.getFileById(parm);*/
			
			FileItem file = null;
			List<FileItem> fileList = cacheController.getFile();
			//if more than 1 file, get 1st one
			String[] ids = id.split("\\,");
			for(FileItem fileItem : fileList){
				if(ids[0].equals(fileItem.getSeq())){
					file = fileItem;
					break;
				}
			}
			
			if(file!=null && file.getFileUrl()!=null && file.getFileUrl().length()>0){
				URL url = new URL(file.getFileUrl());
				is = url.openStream ();
				byte[] imageBytes = IOUtils.toByteArray(is);
				
				res.setContentType("image/gif");
				OutputStream o = res.getOutputStream();
				o.write(imageBytes);
				o.flush();
				o.close();
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally {
		  if (is != null) { is.close(); }
		}
	}
	
}
